<?php

namespace Home\Controller;

use Think\Controller;

/** 
 * @author Administrator
 * 
 */
class DaweiController extends Controller {
    
    public function index(){
        if(IS_POST){
            $url = $_POST['url'];
            preg_match("/daweijita\.com\/(\d+)/i", $url, $math);
            if(!$math){
                $return['flag'] = false;
                $retrun['msg'] = '输入的网址错误';
                $this->ajaxReturn($return);
            }else{
                $id = $math[1];
            }
            
            //查库
            $detail = M('guitar')->where(array('article_id' => $id))->find();
            if($detail){
                $title = $detail['title'];
                $image_urls = unserialize($detail['content']);
            }else{
                //获取页面的收费歌曲
                $snoopy = new \Lain\Snoopy;
                $snoopy->fetch($url);
                $html_code = $snoopy->results;
                $article_query = \QL\QueryList::Query($html_code, array('content' => array('[itemprop="articleBody"]','html'), 'title' => array('h1', 'text')))->data;
                $article_html = $article_query[0]['content'];
                $title = $article_query[0]['title'];
                //判断是否是付费
                //如果是免费， 直接获取图片地址
                $fufei_image_name = $this->get_sub_content($article_html, 'fufei_', '.gif');
                if($fufei_image_name){
                    $insert_data['shoufei'] = 1;
                    $fufei_image_url = $this->getRealImageUrl($fufei_image_name);
                    if($fufei_image_url){
                        //获取相邻的几张
                        $image_urls = $this->getExtendImage($fufei_image_url);
                    }
                }else{
                    //获取免费图片
                    $image_query = \QL\QueryList::Query($article_html, array('content' => array('noscript img','src')))->data;
                    if($image_query){
                        foreach ($image_query as $_k => $_v){
                            $image_urls[] = $image_query[$_k]['content'];
                        }
                    }
                }
                if($image_urls){
                    //保存数据库
                    $insert_data['title'] = $title;
                    $insert_data['article_id'] = $id;
                    $insert_data['content'] = serialize($image_urls);
                    M('guitar')->add($insert_data);
                }
            }
            
            if($image_urls){
                $return['flag'] = true;
                $return['data'] = $image_urls;
                
                //保存到查询记录里
                if(cookie('log')){
                    $log = unserialize(cookie('log'));
                }
                
                $log[$id] = array(
                         'title'    => $title,
                         'url'      => $url
                );
                $cookie_log = serialize($log);
                cookie('log', $cookie_log);
                
            }else{
                $return['flag'] = false;
                $return['msg'] = '查无结果';
            }
            
            $this->ajaxReturn($return);
            
        }else{
            $cookie_log = cookie('log');
            if($cookie_log){
                $cookie_log = unserialize($cookie_log);
                $this->assign('log', $cookie_log);
            }
            $this->display();
        }
    }
    
    //字段截取
    public 	function get_sub_content($content, $start, $end){
		//截取首段
		$start_str = strstr($content, $start);
		//截取尾段
		$image_name = strstr($start_str, $end, true);
		
		//去掉匹配字眼
		$image_name = str_replace(array('fufei_', '_guitar'), '', $image_name);
		return $image_name;
	}
    
    //获取真实的图片地址
    public function getRealImageUrl($fufei_image_name){
        if(!$fufei_image_name)
            return false;
            //要显示的图片宽带
            $image_width = 1200;
            for($year=2011; $year <= 2016; $year++){
                for($month = 1; $month <= 12; $month++){
                    if($month < 10){
                        $month_str = '0'.$month;
                    }else{
                        $month_str = $month;
                    }
                    $urls[] = "http://cdn.daweijita.com/{$year}/{$month_str}/tab_{$fufei_image_name}_1.gif";
                }
            }
            $correctUrls = $this->getCorrectUrls($urls);
            if($correctUrls){
                //取第一个地址
                return $correctUrls[0];
            }else{
                return false;
            }
    }
    
    //并发采集urls， 提取符合条件的url。
    public function getCorrectUrls($urls = array()){
        //并发采集
        $mh = curl_multi_init();
        foreach ($urls as $i => $url) {
            $conn[$i] = curl_init($url);
            curl_setopt($conn[$i], CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)");
            curl_setopt($conn[$i], CURLOPT_HEADER ,0);
            curl_setopt($conn[$i], CURLOPT_CONNECTTIMEOUT,60);
            curl_setopt($conn[$i],CURLOPT_RETURNTRANSFER,true);  // 设置不将爬取代码写到浏览器，而是转化为字符串
            curl_multi_add_handle ($mh,$conn[$i]);
        }
        do {
            curl_multi_exec($mh,$active);
        } while ($active);
        //符合条件的留下
        foreach ($urls as $i => $url) {
            $data = curl_multi_getcontent($conn[$i]); // 获得爬取的代码字符串
            if($data != '{"error":"Document not found"}'){
                $correct_urls[] = $url;
            }
             
        }
         
        foreach ($urls as $i => $url) {
            curl_multi_remove_handle($mh,$conn[$i]);
            curl_close($conn[$i]);
        }
        curl_multi_close($mh);
        return $correct_urls;
    }
    
    //获取相邻的几张图片
    public function getExtendImage($image_url){
        //图片名称
        $extend_image_name = strstr($image_url, '1.gif', true);
        //从第二张开始， 最多限制6张
		for($i = 2; $i < 7; $i++){
			$urls[$i] = $extend_image_name.$i.'.gif';
		}
		$image_urls = array();
		$image_urls = $this->getCorrectUrls($urls);
		//加入第一张图片
		array_unshift($image_urls, $image_url);
		return $image_urls;
    }
}

